﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Security.Cryptography;
using NHibernateDB;
using System.Text;

namespace WSAutentificare
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        private readonly string AUTENTIFICAT = "Autentificat reusita";
        private readonly string NE_AUTENTIFICAT = "Autentificare nereusita";

        public static Dictionary<string, bool> authUsers = new Dictionary<string, bool>();

        [WebMethod]
        public string Autentificare(string user, string pass)
        {
            string clientIP = HttpContext.Current.Request.UserHostAddress;
            MD5 crypt = new MD5CryptoServiceProvider();
            ASCIIEncoding stren = new ASCIIEncoding();
            byte[] hpass;
            string shpass = "";

            try
            {
                PersistenceManager pm = PersistenceManager.Instance;

                // hash the password
                hpass = crypt.ComputeHash(stren.GetBytes(pass));
                foreach (byte b in hpass)
                    shpass += b;

                //Utilizatori u = new Utilizatori();
                //u.Utilizator = user;
                //u.Parola = shpass;
                //pm.Save<Utilizatori>(u);

                // interogate the DB
                IList<Utilizatori> users = pm.RetrieveEquals<Utilizatori>("Utilizator", user,
                                                                          "Parola", shpass);
                if (users.Count != 0)
                {
                    XMLParser parser = new XMLParser();
                    if (!parser.ClientExist(clientIP))
                        parser.WriteClientIP(clientIP);

                    return AUTENTIFICAT;
                }
                else
                {
                    return NE_AUTENTIFICAT;
                }
            }
            catch (Exception x)
            {
                return NE_AUTENTIFICAT;
            }
        }

        [WebMethod]
        public void IesireSesiune()
        {
            string clientIP = HttpContext.Current.Request.UserHostAddress;

            XMLParser parser = new XMLParser();
            if (parser.ClientExist(clientIP))
                parser.DeleteClientIP(clientIP);
        }
    }
}
